package com.spice.im.chat;

import java.net.URISyntaxException;
import java.text.DecimalFormat;
import java.util.ArrayList;



import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jivesoftware.smack.util.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.dodola.model.DuitangInfo;
import com.dodola.model.DuitangInfoAdapter;
import com.dodowaterfall.widget.FlowView;
//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.example.android.bitmapfun.util.Base64;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.R;
import com.spice.im.SimpleListDialog;
import com.spice.im.SimpleListDialogAdapter;
import com.spice.im.SpiceApplication;
import com.spice.im.SimpleListDialog.onSimpleListItemClickListener;
import com.spice.im.chat.ChatPullRefListActivity.StaggeredAdapter;
import com.spice.im.chat.ImageMapUtils.OnMapDownloadStateListener;
import com.spice.im.chat.MessageText.MESSAGE_TYPE;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.ImageFetcher;
import com.spiceim.db.TContactGroup;
import com.spiceim.db.TContactGroupAdapter;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.service.XmppConnectionAdapter;

public class MapMessageItem implements OnLongClickListener,OnClickListener,
OnMapDownloadStateListener{
	private static final String TAG = "MapMessageItem > DeleteMessage";
	private MessageText mMsgText;
	protected Context mContext;
	private int mPosition;
	private StaggeredAdapter mStAdapter = null;
	private String fromAccount;
	private String toAccount;
	private String headimg = "",myheadimg = "";
	private ChatPullRefListActivity mActivity = null;
	private String username = "",myusername = "";
	private HandyTextView message_tv_status_audio = null;//消息发送状态
	private int chattype = 0;//0 单聊 1 群聊自己发送消息 2 群聊接收他人消息
	
	private MESSAGE_TYPE messageType;
	protected LayoutInflater mInflater;
	protected LinearLayout mLayoutMessageContainer;
	protected View mRootView;
	protected int mBackground;
	private LinearLayout mLayoutLeftContainer;
	private FlowView mIvPhotoView;
	
	private HandyTextView message_tv_timestamp;//消息发送/接收时间
	private HandyTextView message_tv_nickname;
	
	private ImageView mIvImage;
	private HandyTextView mIvTextMapAddr;//message_iv_mapaddr
	private LinearLayout mLayoutLoading;
	private ImageView mIvLoading;
//	private ImageMapUtils mImageMapUtils;
	
//	private HandyTextView mHtvLoadingText;

	private AnimationDrawable mAnimation;
	
	private ImageFetcher mImageFetcher;
	
	private String mLongitude;
	private String mLatitude;
	private String mGpsAddr;
	
	private DuitangInfo duitangInfo = null;
	private DuitangInfoAdapter duitangInfoAdapter = null;//用户信息存入本地数据库
	private TContactGroupAdapter tContactGroupAdapter = null;
	private TContactGroup tg = null;
	private SimpleListDialog mDialog = null;
	private MessageAdapter messageAdapter = null;//删除本地数据库用户聊天记录
	
	public MapMessageItem(Context context,
			MessageText msgText,
			int position,
			StaggeredAdapter stAdapter,
			String _fromAccount,
			String _toAccount,
			String _headimg,
			String _myheadimg,
			ChatPullRefListActivity activity,
			String _username,
			String _myusername){
		mMsgText = msgText;
		mContext = context;
		mPosition = position;
		mStAdapter = stAdapter;
		fromAccount = _fromAccount;
		toAccount = _toAccount;
		headimg = _headimg;
		myheadimg = _myheadimg;
		mActivity = activity;
		username = _username;
		myusername = _myusername;
		//群聊：mMsgText.getBareJid()=20140508@conference.pc2011040521xsg/18901203590;fromAccount=18901203590@pc2011040521xsg/Beem;toAccount=20140508@conference.pc2011040521xsg
		//单聊：06-05 22:23:25.549: ERROR/※※※※※20140605(1)※※※※※(10831): ※※mMsgText.getBareJid()=Me;fromAccount=18901203590@pc2011040521xsg/Beem;toAccount=18901159737@pc2011040521xsg
		//单聊: 06-05 22:23:25.549: ERROR/※※※※※20140605(2)※※※※※(10831): ※※mMsgText.getBareJid()=;fromAccount=18901203590;toAccount=18901159737@pc2011040521xsg
		Log.e("※※※※※####20140807####※※※※※", "※※mMsgText.getIsOffline()="+mMsgText.getIsOffline());
		Log.e("※※※※※20140605(1)※※※※※", "※※mMsgText.getBareJid()="+mMsgText.getBareJid()+";fromAccount="+fromAccount+";toAccount="+toAccount);
		Log.e("※※※※※20140605(2)※※※※※", "※※mMsgText.getBareJid()="+StringUtils.parseResource(mMsgText.getBareJid())+";fromAccount="+StringUtils.parseName(fromAccount)+";toAccount="+toAccount);
		String temp2 = StringUtils.parseResource(mMsgText.getBareJid());
		if(temp2!=null && temp2.startsWith("/"))
			temp2 = temp2.substring(1);//"/3"
		if(StringUtils.parseResource(mMsgText.getBareJid())!=null 
				&& temp2.length()!=0
				&& !temp2.equalsIgnoreCase("Beem")
				&& temp2.equals(StringUtils.parseName(fromAccount)))
			chattype = 1;
		else if(StringUtils.parseResource(mMsgText.getBareJid())!=null 
				&& temp2.length()!=0
				&& !temp2.equalsIgnoreCase("Beem")
				&& !temp2.equals(StringUtils.parseName(fromAccount)))
			chattype = 2;
		else
			chattype = 0;
		duitangInfoAdapter = DuitangInfoAdapter.getInstance(mContext);
		tContactGroupAdapter = TContactGroupAdapter.getInstance(mContext);
		messageType = mMsgText.getMessageType();
		
//		initNameImg();
		
		//20121224 start
		messageAdapter = MessageAdapter.getInstance(mContext);
		mLoadingDialog = new FlippingLoadingDialog(mContext, "请求提交中");
		String[] codes = new String[] { "复制","删除","转发" };//分享,翻译
		mDialog = new SimpleListDialog(context);
		mDialog.setTitle("提示");
		mDialog.setTitleLineVisibility(View.GONE);
		mDialog.setAdapter(new SimpleListDialogAdapter(context, codes));
		mDialog.setOnSimpleListItemClickListener(new OnReplyDialogItemClickListener(
				));
		//20141224 end
		
//		Log.e("※※※※※####20140806####※※※※※", "※※messageType="+messageType+
//				";mMsgText.getBareJid()="+mMsgText.getBareJid()+
//				";key="+StringUtils.parseResource(mMsgText.getBareJid())+
//				";key2="+StringUtils.parseName(fromAccount));
		mInflater = LayoutInflater.from(context);
		switch (messageType) {
		case RECEIVER:
//			mRootView = mInflater.inflate(R.layout.specialchatting_item_to_picture,
//					null);
			//message_send_template.xml
			mRootView = mInflater.inflate(R.layout.message_send_template,
					null);
			mBackground = R.drawable.bg_message_box_send;
			break;

		case SEND:
//			mRootView = mInflater.inflate(R.layout.specialchatting_item_from_picture,
//					null);
			//message_receive_template.xml
			mRootView = mInflater.inflate(R.layout.message_receive_template,
					null);
			mBackground = R.drawable.bg_message_box_receive;
			message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
			break;
		case conference:
//			mRootView = mInflater.inflate(R.layout.specialmultichatting_item_to_picture,
//					null);
////			mBackground = R.drawable.bg_message_box_receive;
			if(mMsgText.getBareJid().indexOf("@1")==-1){//自己发给群
				mRootView = mInflater.inflate(R.layout.message_receive_template,
						null);
				mBackground = R.drawable.bg_message_box_receive;
				message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
			}else{
				String key = StringUtils.parseResource(mMsgText.getBareJid());
				if(key!=null && key.startsWith("/"))
					key = key.substring(1);//"/18901203590"
				String key2 = StringUtils.parseName(fromAccount);
				if(key.equals(key2)){//自己发给群
					mRootView = mInflater.inflate(R.layout.message_receive_template,
							null);
					mBackground = R.drawable.bg_message_box_receive;
					message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
				}else{
					//message_send_template.xml
					mRootView = mInflater.inflate(R.layout.message_send_template,
							null);
					mBackground = R.drawable.bg_message_box_send;
					message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
				}
			}
			break;
		}

		if(msgText.getMessage().startsWith("<transferfile mode=")
				|| msgText.getMessage().startsWith("<transferfile transt='offline' mode=")){//文件
            // 首先匹配img标签内的内容
            String img_regex = "<(?i)transferfile(.*?)>(.*?)</(?i)transferfile>";//img
            Pattern p = Pattern.compile(img_regex);
            Matcher m = p.matcher(msgText.getMessage());
            
            String src_alt;
            String img_name;
            String src_type="";
            String filelength="";
            while(m.find()){

                src_alt=m.group(1);
                img_name=m.group(2);
                if(null==src_alt && null==img_name){
                    continue;
                }
                
                // 匹配src中的内容
                String src_reg = "mode=\'(.*?)\'";//src
                Pattern src_p = Pattern.compile(src_reg);
                Matcher src_m = src_p.matcher(src_alt);
                while(src_m.find()){
//                    System.out.println("mode是：" + src_m.group(1));
                }
                
                // 匹配alt中的内容
                String alt_reg = "type=\'(.*?)\'";//alt
                Pattern alt_p = Pattern.compile(alt_reg);
                Matcher alt_m = alt_p.matcher(src_alt);
                while(alt_m.find()){
//                    System.out.println("type是：" + alt_m.group(1));
                	src_type = alt_m.group(1);
                	 System.out.println("type是：" +src_type);

                }                
                // 匹配filelength中的内容
                String filelength_reg = "filelength=\'(.*?)\'";//alt
                Pattern filelength_p = Pattern.compile(filelength_reg);
                Matcher filelength_m = filelength_p.matcher(src_alt);
                while(filelength_m.find()){
                	filelength = filelength_m.group(1);
                	System.out.println("时长:"+filelength+"秒");//录音时长
                	
//                    System.out.println("filelength是：" + filelength_m.group(1));
//                    holder.text = (TextView) convertView.findViewById(R.id.chatting_content_itv);
//                    holder.contentView.setText("时长:"+filelength_m.group(1)+"秒");//录音时长
                } 
                
// 				File file = new File(img_name);
				String temp = img_name.substring(img_name.lastIndexOf(".")+1);
//				if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && file.exists() &&
				if( //file.exists() &&		
						(temp.equalsIgnoreCase("jpg")
						|| temp.equalsIgnoreCase("png")
						|| temp.equalsIgnoreCase("gif")
						|| temp.equalsIgnoreCase("bmp"))){
//					mPicPath = img_name;
				}else{
					//img,audio,video,other
					if(src_type.equals("audio")){//amr
//						mRecordPath = img_name;
//						mRecord_Time = Float.valueOf(filelength);
					}else if(src_type.equals("video"))
						;
					else if(src_type.equals("map")){
						Log.e("※※※※※20141013MapMessageItem※※※※※", "※※img_name="+img_name);
						String[] xy = img_name.split(",");
						mLongitude = xy[0];
						Log.e("※※※※※20141013MapMessageItem※※※※※", "※※mLongitude="+mLongitude);
						mLatitude = xy[1];
						Log.e("※※※※※20141013MapMessageItem※※※※※", "※※mLatitude="+mLatitude);
						if(xy.length == 3){
							mGpsAddr = xy[2];
							Log.e("※※※※※20141013MapMessageItem※※※※※", "※※mGpsAddr="+mGpsAddr);
						}
						
					}else 
						;
				}
            }
            
		}
		
		
//		if (mRootView != null) {
		mLayoutMessageContainer = (LinearLayout) mRootView
		.findViewById(R.id.message_layout_messagecontainer);
		mLayoutMessageContainer.setBackgroundResource(mBackground);
		
		mLayoutLeftContainer = (LinearLayout) mRootView
		.findViewById(R.id.message_layout_leftcontainer);
		mIvPhotoView = (FlowView) mRootView.findViewById(R.id.message_iv_userphoto);
		
		message_tv_timestamp = (HandyTextView)mRootView.findViewById(R.id.message_tv_timestamp);
		message_tv_nickname = (HandyTextView)mRootView.findViewById(R.id.message_tv_nickname);

//		mImageMapUtils = ImageMapUtils.create(context);
		
        mImageFetcher = new ImageFetcher(context, 240);
        mImageFetcher.setUListype(1);
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
        mImageFetcher.setExitTasksEarly(false);
        
		onInitViews();		
	}
//	@Override
	protected void onInitViews() {
		View view = mInflater.inflate(R.layout.message_map, null);
		mLayoutMessageContainer.addView(view);
		mIvImage = (ImageView) view.findViewById(R.id.message_iv_mapimage);
		mIvTextMapAddr = (HandyTextView) view.findViewById(R.id.message_iv_mapaddr);
		if(mGpsAddr!=null 
				&& !mGpsAddr.equalsIgnoreCase("null")
				&& mGpsAddr.length()!=0)
		mIvTextMapAddr.setText(new String(Base64.decode(mGpsAddr.getBytes())));
		mLayoutLoading = (LinearLayout) view
				.findViewById(R.id.message_layout_maploading);
		mIvLoading = (ImageView) view.findViewById(R.id.message_iv_maploading);
		mIvImage.setOnClickListener(this);
		mIvImage.setOnLongClickListener(this);
		mLayoutMessageContainer.setOnClickListener(this);
		mLayoutMessageContainer.setOnLongClickListener(this);
		
		
		
        //设置你目的地的经纬度
        mInfo.setLat(Double.valueOf(mLatitude));
        mInfo.setLng(Double.valueOf(mLongitude));
        
        mapSheetView = LayoutInflater.from(mContext).inflate(R.layout.map_navagation_sheet, null);
        mBaiduBtn = (Button)mapSheetView.findViewById(R.id.baidu_btn);
        mGaodeBtn = (Button)mapSheetView.findViewById(R.id.gaode_btn);
        mTencentBtn = (Button)mapSheetView.findViewById(R.id.tencent_btn);
        mCancel2Btn = (Button)mapSheetView.findViewById(R.id.cancel_btn2);

        mBaiduBtn.setOnClickListener(this);
        mGaodeBtn.setOnClickListener(this);
        mTencentBtn.setOnClickListener(this);
        mCancel2Btn.setOnClickListener(this);
	}
	String headpath = "";
	protected void onFillMessage() {
		mLayoutLeftContainer.setVisibility(View.VISIBLE);
		switch (messageType) {
			case RECEIVER:
//				mImageFetcher.loadImage(headimg, mIvPhotoView);
//				message_tv_nickname.setText(username);
				if(mMsgText.getBareJid().indexOf("@1")==-1){
//	        		try{
//	        			headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
//	        		if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()))!=null){
//	        			headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName().length()!=0)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getUsername());
//	        		}else{
//	        			headpath = "";
//	        			message_tv_nickname.setText(mMsgText.getBareJid());
//	        		}
	        		
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
					if(tg!=null){
						headpath = tg.getAvatarPath();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(mMsgText.getBareJid());
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key!=null && key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
					
//	        		try{
//	        			headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
////					message_tv_nickname.setText("uid为"+key);
////					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress("2@0")).getName());
//	        		if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//	        			headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//	        		}else{
//	        			headpath = "";
//	        			message_tv_nickname.setText(key+"@0");
//	        		}
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
					if(tg!=null){
						headpath = tg.getAvatarPath();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
					}
				}
//				mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
				if(headpath!=null
	    	    		&& headpath.length()!=0
	    	    		&& !headpath.equalsIgnoreCase("null"))
//	    	    	ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
				ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
	    	    else
	    	    	mIvPhotoView.setImageResource(R.drawable.empty_photo4);
				break;
			case SEND:
//				mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//				message_tv_nickname.setText(myusername);
				if(mMsgText.getBareJid().indexOf("@1")==-1){
//					try{
//						headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
//					if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()))!=null){
//						headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName().length()!=0)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getUsername());
//					}else{
//						headpath = "";
//						message_tv_nickname.setText(StringUtils.parseBareAddress(mMsgText.getBareJid()));//"空"+
//					}
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
					if(tg!=null){
						headpath = tg.getAvatarPath();
//						Toast toast = Toast.makeText(mContext, "我的tg="+tg.toXML()+"头像avatar="+tg.getAvatar()+";avatarpath="+tg.getAvatarPath(), Toast.LENGTH_LONG);
//			    	    toast.show();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(mMsgText.getBareJid()));//"空"+
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key!=null && key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
//					try{
//						headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
////					message_tv_nickname.setText("uid为"+key);
////					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress("2@0")).getName());
//					if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//						headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//					}else{
//						headpath = "";
//						message_tv_nickname.setText(key+"@0");
//					}
					
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
					if(tg!=null){
						headpath = tg.getAvatarPath();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
					}
				}
//				mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
				if(headpath!=null
	    	    		&& headpath.length()!=0
	    	    		&& !headpath.equalsIgnoreCase("null"))
//	    	    	ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
				ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
	    	    else
	    	    	mIvPhotoView.setImageResource(R.drawable.empty_photo4);
				break;
			case conference:
				Log.e("※※※※※2014080508050805※※※※※", "※※fromAccount="+fromAccount+";toAccount="+toAccount);
//				if(mMsgText.getBareJid().indexOf("@conference.")==-1){//自己发给群
//					mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//					message_tv_nickname.setText(myusername);
//				}else{
//					String key = StringUtils.parseResource(mMsgText.getBareJid());
//					if(key.startsWith("/"))
//						key = key.substring(1);//"/18901203590"
//					String key2 = StringUtils.parseName(fromAccount);
//					if(key.equals(key2)){//自己发给群
//						mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//						message_tv_nickname.setText(myusername);
//					}else{
////						Contact contact = mActivity.mListContact.get(key);
////						String url = "";
////						if(contact!=null){
////							message_tv_nickname.setText(contact.getName());
////				            if(contact.getAvatarId()!=null 
////				            		&& contact.getAvatarId().length()!=0 
////				            		&& !contact.getAvatarId().equalsIgnoreCase("null")
////				            		&& (
////				            				contact.getAvatarId().toLowerCase().endsWith(".jpg")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".png")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".bmp")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".gif")
////				            			))
////				            	url = XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(contact.getJID())+"/"+"thumbnail_"+contact.getAvatarId();
////						}
////						if(url!=null && url.length()!=0)
////							mImageFetcher.loadImage(url, mIvPhotoView);
//						mImageFetcher.loadImage(headimg, mIvPhotoView);
//						message_tv_nickname.setText(username);
//					}
//				}
				if(mMsgText.getBareJid().indexOf("@1")==-1){//自己发给群
////					mImageFetcher.loadImage(myheadimg, mIvPhotoView);
////					message_tv_nickname.setText(myusername);
//					try{
//						headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
//					if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()))!=null){
//						headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getAvatarPath();
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName()!=null)
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
//					}else{
//						headpath = "";
//						message_tv_nickname.setText(mMsgText.getBareJid());
//					}
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
					if(tg!=null){
						headpath = tg.getAvatarPath();
//						Toast toast = Toast.makeText(mContext, "我的tg="+tg.toXML()+"头像avatar="+tg.getAvatar()+";avatarpath="+tg.getAvatarPath(), Toast.LENGTH_LONG);
//			    	    toast.show();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(mMsgText.getBareJid()));//"空"+
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key!=null && key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
//					try{
//						headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//	        		}catch(Exception e){
//	        			e.printStackTrace();
//	        		}
					String key2 = StringUtils.parseName(fromAccount);
					if(key.equals(key2)){//自己发给群
////						mImageFetcher.loadImage(myheadimg, mIvPhotoView);
////						message_tv_nickname.setText(myusername);
////						message_tv_nickname.setText("uid为"+key);
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//							headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getAvatarPath();
//							if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null && tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//								message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//							else
//								message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//						}else{
//							headpath = "";
//							message_tv_nickname.setText(key+"@0");
//						}
						
						tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
						if(tg!=null){
							headpath = tg.getAvatarPath();
							if(tg.getName()!=null && tg.getName().length()!=0)
								message_tv_nickname.setText(tg.getName());
							else
								message_tv_nickname.setText(tg.getUsername());
						}else{
							headpath = "";
							message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
						}
					}else{
////						Contact contact = mActivity.mListContact.get(key);
////						String url = "";
////						if(contact!=null){
////							message_tv_nickname.setText(contact.getName());
////				            if(contact.getAvatarId()!=null 
////				            		&& contact.getAvatarId().length()!=0 
////				            		&& !contact.getAvatarId().equalsIgnoreCase("null")
////				            		&& (
////				            				contact.getAvatarId().toLowerCase().endsWith(".jpg")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".png")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".bmp")
////				            				|| contact.getAvatarId().toLowerCase().endsWith(".gif")
////				            			))
////				            	url = XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(contact.getJID())+"/"+"thumbnail_"+contact.getAvatarId();
////				            if(url!=null && url.length()!=0)
////								mImageFetcher.loadImage(url, mIvPhotoView);
////						}else{
////							mImageFetcher.loadImage(headimg, mIvPhotoView);
////							message_tv_nickname.setText(username);
//							if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//								headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getAvatarPath();
//								if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null
//										&& tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0
//										&& !tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().equalsIgnoreCase("null"))
//									message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());
//								else
//									message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//							}else{
//								headpath = "";
//								message_tv_nickname.setText(key+"@0");
//							}
////							message_tv_nickname.setText(key);
////						}
////						if(url!=null && url.length()!=0)
////							mImageFetcher.loadImage(url, mIvPhotoView);
						
						
						tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
						if(tg!=null){
							headpath = tg.getAvatarPath();
							if(tg.getName()!=null && tg.getName().length()!=0 && !tg.getName().equalsIgnoreCase("null"))
								message_tv_nickname.setText(tg.getName());
							else
								message_tv_nickname.setText(tg.getUsername());
						}else{
							headpath = "";
							message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
						}
					}
				}
//				mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
				if(headpath!=null
	    	    		&& headpath.length()!=0
	    	    		&& !headpath.equalsIgnoreCase("null"))
//	    	    	ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
				ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView,SpiceApplication.getInstance().options);
	    	    else
	    	    	mIvPhotoView.setImageResource(R.drawable.empty_photo4);
				break;
		
		}
		message_tv_timestamp.setText(mMsgText.getTimestamp().toLocaleString());
		downloadMap();
	}
	
	private void downloadMap() {
//		mImageMapUtils.setOnMapDownloadStateListener(this);
////		mImageMapUtils.display(BeemApplication.getInstance().mLongitude, BeemApplication.getInstance().mLatitude);
//		mImageMapUtils.display(Double.valueOf(mLongitude).doubleValue(), Double.valueOf(mLatitude).doubleValue());
		String data = "http://api.map.baidu.com/staticimage?center="+mLongitude+","+mLatitude+"&width=256&height=128&zoom=13";
		path = data;
		mImageFetcher.loadNormalImage(data, mIvImage, 1, 256, 128,mHandler);
		mHandler.sendEmptyMessage(0);
	}
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				startLoadingAnimation();
				break;

			case 1:
				path=msg.obj.toString();
				stopLoadingAnimation(path);
				break;
			case 2:
				stopLoadingAnimation(null);
				if(message_tv_status_audio!=null){
			    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_read2);
			    	message_tv_status_audio.setText("送达");
			    }
				break;
			case 3:
				if(mStAdapter!=null){
					mStAdapter.deleteMsg(mPosition);
					mStAdapter.notifyDataSetChanged();
				}
				break;
			}
		}

	};

	@SuppressWarnings("deprecation")
	private Drawable getDrawable(int id) {
		return new BitmapDrawable(BitmapFactory.decodeResource(
				mContext.getResources(), id));
	}

	@Override
	public void onStart() {
		mHandler.sendEmptyMessage(0);
	}

	@Override
	public void onFinish(String path) {
		android.os.Message msg = mHandler.obtainMessage();
		msg.what = 1;
		msg.obj = path;
		msg.sendToTarget();
	}
	
	
	private BottomSheetPop mBottomSheetPop;
    private View mapSheetView;
    private Button mBaiduBtn;
    private Button mGaodeBtn;
    private Button mTencentBtn;
    private Button mCancel2Btn;
    AddressInfo mInfo = new AddressInfo();
    
	private String path= "";
	@Override
	public void onClick(View v) {
//		Intent intent = new Intent(mContext, ImageBrowserActivity.class);
//		intent.putExtra(ImageBrowserActivity.IMAGE_TYPE,
//				ImageBrowserActivity.TYPE_PHOTO);
////		intent.putExtra("path", getMessage());//消息内容
////		intent.putExtra("path", "e33455fc-da75-44f8-ab91-605f8bbcac97.jpg");
//		intent.putExtra("path", path);
//		mContext.startActivity(intent);
//		if(mActivity != null)
//			((ChatPullRefListActivity) mContext).overridePendingTransition(R.anim.zoom_enter,0);
		
		
        switch (v.getId()) {
        case R.id.message_iv_mapimage:
            mBottomSheetPop = new BottomSheetPop(mContext);
            mBottomSheetPop.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
            mBottomSheetPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            mBottomSheetPop.setContentView(mapSheetView);
            mBottomSheetPop.setBackgroundDrawable(new ColorDrawable(0x00000000));
            mBottomSheetPop.setOutsideTouchable(true);
            mBottomSheetPop.setFocusable(true);
            mBottomSheetPop.showAtLocation(((Activity)mContext).getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
            break;
        case R.id.cancel_btn2:
            if (mBottomSheetPop != null) {
                mBottomSheetPop.dismiss();
            }
            break;
        case R.id.baidu_btn:
            if (isAvilible(mContext, "com.baidu.BaiduMap")) {//传入指定应用包名
                try {
                    Intent intent = Intent.getIntent("intent://map/direction?" +
                            "destination=latlng:" + mInfo.getLat() + "," + mInfo.getLng() + "|name:我的目的地" +        //终点
                            "&mode=driving&" +          //导航路线方式
                            "&src=appname#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                    mContext.startActivity(intent); //启动调用
                } catch (URISyntaxException e) {
                    Log.e("intent", e.getMessage());
                }
            } else {//未安装
                //market为路径，id为包名
                //显示手机上所有的market商店
                Toast.makeText(mContext, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
                Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                if (intent.resolveActivity(mContext.getPackageManager()) != null){
                	mContext.startActivity(intent);
                }
            }
            mBottomSheetPop.dismiss();
            break;
        case R.id.gaode_btn:
            if (isAvilible(mContext, "com.autonavi.minimap")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_DEFAULT);

                //将功能Scheme以URI的方式传入data
                Uri uri = Uri.parse("androidamap://navi?sourceApplication=appname&poiname=fangheng&lat=" + mInfo.getLat() + "&lon=" + mInfo.getLng() + "&dev=1&style=2");
                intent.setData(uri);

                //启动该页面即可
                mContext.startActivity(intent);
            } else {
                Toast.makeText(mContext, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
                Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                if (intent.resolveActivity(mContext.getPackageManager()) != null){
                	mContext.startActivity(intent);
                }
            }
            mBottomSheetPop.dismiss();
            break;
        case R.id.tencent_btn:
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);

            //将功能Scheme以URI的方式传入data
            Uri uri = Uri.parse("qqmap://map/routeplan?type=drive&to=我的目的地&tocoord=" + mInfo.getLat() + "," + mInfo.getLng());
            intent.setData(uri);
            if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                //启动该页面即可
            	mContext.startActivity(intent);
            } else {
                Toast.makeText(mContext, "您尚未安装腾讯地图", Toast.LENGTH_LONG).show();
            }
            mBottomSheetPop.dismiss();
            break;
        }
	}
	/**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public static boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }
	@Override
	public boolean onLongClick(View v) {
//		return false;
		if(mDialog!=null)
			mDialog.show();
		return true;
	}
	private void startLoadingAnimation() {
		if (mAnimation != null) {
			mAnimation.stop();
			mAnimation = null;
		}
		mAnimation = new AnimationDrawable();
		mAnimation.addFrame(getDrawable(R.drawable.ic_loading_msgplus_01), 300);
		mAnimation.addFrame(getDrawable(R.drawable.ic_loading_msgplus_02), 300);
		mAnimation.addFrame(getDrawable(R.drawable.ic_loading_msgplus_03), 300);
		mAnimation.addFrame(getDrawable(R.drawable.ic_loading_msgplus_04), 300);
		mAnimation.setOneShot(false);
//		mIvImage.setVisibility(View.GONE);
		mLayoutLoading.setVisibility(View.VISIBLE);
		mIvLoading.setVisibility(View.VISIBLE);
//		mHtvLoadingText.setVisibility(View.VISIBLE);
		mIvLoading.setImageDrawable(mAnimation);
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				try{
					if(mAnimation != null)
						mAnimation.start();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
//		mHandler.sendEmptyMessage(1);
	}

	private void stopLoadingAnimation(String path) {
		if (mAnimation != null) {
			mAnimation.stop();
			mAnimation = null;
		}
		mLayoutLoading.setVisibility(View.GONE);
//		mHtvLoadingText.setVisibility(View.GONE);
		mIvImage.setVisibility(View.VISIBLE);
		mIvTextMapAddr.setVisibility(View.VISIBLE);
//		if (path != null) {
//			mIvImage.setImageBitmap(PhotoUtils.getBitmapFromFile(path));
//		}
	}
	
	public View getRootView() {
		return mRootView;
	}
	
	public void initNameImg(){
		switch (messageType) {
			case RECEIVER:
				if(headimg==null
						|| headimg.equalsIgnoreCase("null")
						|| headimg.length()==0
						|| username==null
						|| username.equalsIgnoreCase("null")
						|| username.length()==0){
					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));//toAccount
					if(duitangInfo!=null){
						headimg = duitangInfo.getIsrc();
						username = duitangInfo.getName();
					}else{
						headimg = "";
						username = StringUtils.parseName(mMsgText.getBareJid());
					}
				}
//				if(myheadimg==null
//						|| myheadimg.equalsIgnoreCase("null")
//						|| myheadimg.length()==0
//						|| myusername==null
//						|| myusername.equalsIgnoreCase("null")
//						|| myusername.length()==0){
//					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
//					if(duitangInfo!=null){
//						myheadimg = duitangInfo.getIsrc();
//						myusername = duitangInfo.getName();
//					}else{
//						myheadimg = "";
//						myusername = StringUtils.parseName(fromAccount);
//					}
//				}
				break;
			case SEND:
//				if(headimg==null
//						|| headimg.equalsIgnoreCase("null")
//						|| headimg.length()==0
//						|| username==null
//						|| username.equalsIgnoreCase("null")
//						|| username.length()==0){
//					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
//					if(duitangInfo!=null){
//						headimg = duitangInfo.getIsrc();
//						username = duitangInfo.getName();
//					}else{
//						headimg = "";
//						username = StringUtils.parseName(fromAccount);
//					}
//				}
				if(myheadimg==null
						|| myheadimg.equalsIgnoreCase("null")
						|| myheadimg.length()==0
						|| myusername==null
						|| myusername.equalsIgnoreCase("null")
						|| myusername.length()==0){
					if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
						duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
					else
						duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));
					if(duitangInfo!=null){
						myheadimg = duitangInfo.getIsrc();
						myusername = duitangInfo.getName();
					}else{
						myheadimg = "";
						if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
							myusername = StringUtils.parseName(fromAccount);
						else
							myusername = StringUtils.parseName(mMsgText.getBareJid());//toAccount
					}
				}
				break;
			case conference:
				if(mMsgText.getBareJid().indexOf("@conference.")==-1){//自己发给群
					if(myheadimg==null
							|| myheadimg.equalsIgnoreCase("null")
							|| myheadimg.length()==0
							|| myusername==null
							|| myusername.equalsIgnoreCase("null")
							|| myusername.length()==0){
						if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
							duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
						else
							duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));
						if(duitangInfo!=null){
							myheadimg = duitangInfo.getIsrc();
							myusername = duitangInfo.getName();
						}else{
							myheadimg = "";
							if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
								myusername = StringUtils.parseName(fromAccount);
							else
								myusername = StringUtils.parseName(mMsgText.getBareJid());
						}
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key!=null && key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
					String key2 = StringUtils.parseName(fromAccount);
					if(key.equals(key2)){//自己发给群
						if(myheadimg==null
								|| myheadimg.equalsIgnoreCase("null")
								|| myheadimg.length()==0
								|| myusername==null
								|| myusername.equalsIgnoreCase("null")
								|| myusername.length()==0){
							duitangInfo = duitangInfoAdapter.getDuitangInfo(key);
							if(duitangInfo!=null){
								myheadimg = duitangInfo.getIsrc();
								myusername = duitangInfo.getName();
							}else{
								myheadimg = "";
								myusername = key;
							}
						}
					}else{
						//message_send_template.xml
						if(headimg==null
								|| headimg.equalsIgnoreCase("null")
								|| headimg.length()==0
								|| username==null
								|| username.equalsIgnoreCase("null")
								|| username.length()==0){
							duitangInfo = duitangInfoAdapter.getDuitangInfo(key);
							if(duitangInfo!=null){
								headimg = duitangInfo.getIsrc();
								username = duitangInfo.getName();
							}else{
								headimg = "";
								username = key;
							}
						}
					}
				}
				
//				Log.e("※※※※※20141020※※※※※", "※※消息TextMessageItem=>mMsgText.getBareJid()="
//						+mMsgText.getBareJid()
//						+";mMsgText.getMTo()="
//						+mMsgText.getMTo()
//						+";key="
//						+StringUtils.parseResource(mMsgText.getBareJid())
//						+";key2="
//						+StringUtils.parseName(fromAccount));
				break;
			default:
				break;
		
		}
	}
	
	
	
	private class OnReplyDialogItemClickListener implements
	onSimpleListItemClickListener {
		
		public OnReplyDialogItemClickListener() {
		}
		@Override
		public void onItemClick(int position) {
			// "复制","删除","转发" };//分享,翻译
			switch (position) {
				case 0:
					copy(mMsgText.getMessage());
					break;
				case 1:
					startDelete();
					break;
				case 2:
//					ClipboardManager m = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
//					m.setText(mMsgText.getMessage());
//		        	Intent intent = new Intent(mContext, BulkMsgContactListPullRefListActivity.class);//BulkMsgContactListPullRefListActivity
//		        	intent.putExtra("myheadimg", myheadimg);
//		        	intent.putExtra("myusername", myusername);
//		        	
//		        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		        	mContext.startActivity(intent);
//		        	if(mActivity != null)
//		        		((ChatPullRefListActivity)mContext).finish();
//		        	else if(mActivity_bulkmsg !=null)
//		        		((BulkMsgChatPullRefListActivity)mContext).finish();
					break;
			}
		}
	}
	private void copy(String text) {
		ClipboardManager m = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
		m.setText(text);
		showCustomToast("已成功复制文本:"+text);
	}
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(mContext).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(mContext);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected FlippingLoadingDialog mLoadingDialog;
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
//		mAsyncTasks.add(asyncTask.execute());
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}

	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
	private void startDelete() {
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在删除,请稍候...");
				Log.e("MMMMMMMMMMMM20141224DeleteMessageMMMMMMMMMMMM", "++++++++++++++20141224DeleteMessage="+mMsgText.getId());
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
				    messageAdapter.deleteMessage(mMsgText.getId());
				} catch (Exception e) {
				    Log.e(TAG, e.getMessage());
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (!result) {
					showCustomToast("删除失败...");
				}else{
					showCustomToast("删除成功...");
					mHandler.sendEmptyMessage(3);
				}
				
				
			}

		});
	}
	
	public String sprintf(String format, double number) {
		return new DecimalFormat(format).format(number);
	}
	//sizeType :big,middle,small
	//type : real 或 ""
	public String avatar_file(int uid, String sizeType, String type) {
		String var = "avatarfile_" + uid + "_" + sizeType + "_" + type;
		String avatarPath = "";
			uid = Math.abs(uid);
			String struid = sprintf("000000000", uid);
			String dir1 = struid.substring(0, 3);
			String dir2 = struid.substring(3, 5);
			String dir3 = struid.substring(5, 7);
			StringBuffer avater = new StringBuffer();
			avater.append(dir1 + "/" + dir2 + "/" + dir3 + "/" + struid.substring(struid.length() - 2));
			avater.append("real".equals(type) ? "_real_avatar_" : "_avatar_");
			avater.append(sizeType + ".jpg");
			avatarPath = avater.toString();

		return avatarPath;
	}
}
